<template>
  <div class="all">
    <Header title="探视排班维护"
    @click-left="back"></Header>
    <el-table
      @row-click="onRowClick"
      class="tableBox"
      ref="tables"
      v-loading="loadingShow"
      element-loading-text="数据正在加载中..."
      :data="tableData"
      border
      @cell-click="handle"
      :header-cell-class-name="cellClass"
      @select="handleRow"
      @header-click="tableHeader"
      @selection-change="handleSelectionChange"
      :height="tabHeight"
      :header-cell-style="{background:'#1da4f2',color:'#fff', textAlign:'center'}"
      style="width: 100%;font-size: 15px">
      <div slot="empty">
        <div>
          <img src="../../../assets/空两本书.png" alt="" width="140" height="140" />
        </div>
        <p :style="{'marginTop': '5px'}">暂无探视排班记录</p>
      </div>
      <el-table-column
        fixed
        type="selection"
        align="center"
        width="60">
      </el-table-column>
      <el-table-column
        prop="dateday"
        label="日期"
        width="100"
        align="center"
        :render-header="renderHeader"
      >
        <template slot-scope="scope">
          <div >
            {{scope.row.dateday ? Common.formatDate(scope.row.dateday , 'mm-dd') :
            new Date().getTime() >= new Date(scope.row.dateday).getTime() ? '空' :
              '请选择'}}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="start_time"
        label="开始时间"
        width="110"
        align="center"
        :render-header="renderHeader"
      >
        <template slot-scope="scope">
          <div >
            {{ scope.row.start_time ? scope.row.start_time :
            new Date().getTime() >= new Date(scope.row.dateday).getTime() ? '空' :
            '请选择' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="end_time"
        label="结束时间"
        width="110"
        align="center"
        :render-header="renderHeader"
      >
        <template slot-scope="scope">
          {{ scope.row.end_time ? scope.row.end_time :
          new Date().getTime() >= new Date(scope.row.dateday).getTime() ? '空' :
            '请选择'}}
        </template>
      </el-table-column>
      <el-table-column
        prop="visit_num"
        label="人数"
        width="100"
        :render-header="renderHeader"
      >
        <template slot-scope="scope">
          <div >
            <el-input size="small"
                      :readonly="new Date().getTime() >= new Date(scope.row.dateday).getTime()"
                      @blur="handleInputBlur(scope.row)"
                      v-model="scope.row.visit_num"
                      :placeholder="new Date().getTime() >= new Date(scope.row.dateday).getTime() ? '空' : '请输入'"
            ></el-input>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="keepBottom" >
      <button @click="add">新增</button>
      <button @click="clickDelete">
        删除
      </button>
    </div>
    <van-popup
      v-model="dateShow"
      round
      position="bottom"
    >
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="dateConfirm"
        @cancel="dateShow = false"
        :formatter="formatter"
      />
    </van-popup>
    <van-popup v-model="TimeShow" round position="bottom">
      <van-picker show-toolbar
                  @cancel="TimeShow = false"
                  @confirm="timeConfirm"
                  title="开始时间和结束时间" :columns="Timecolumns" />
    </van-popup>
    <van-dialog v-model="cancelShow"
                width="80%"
                confirm-button-color="#1da4f2"
                title="确认删除此条数据吗？"
                @confirm="deleteConfirm()"
                show-cancel-button>
    </van-dialog>
    <pop_select :show="date_ShaixuanShow"
                title="选择日期"
                height="70%"
                @confirmMethod="filter"
                @close="date_ShaixuanShow = false"
                :dataList="dateList">
    </pop_select>
    <pop_select :show="start_ShaixuanShow"
                title="选择开始时间"
                height="70%"
                @confirmMethod="filter"
                @close="start_ShaixuanShow = false"
                :dataList="shartList">
    </pop_select>
    <pop_select :show="end_ShaixuanShow"
                title="选择结束时间"
                height="70%"
                @confirmMethod="filter"
                @close="end_ShaixuanShow = false"
                :dataList="endList">
    </pop_select>
    <pop_select :show="visit_ShaixuanShow"
                title="选择人数"
                height="70%"
                @confirmMethod="filter"
                @close="visit_ShaixuanShow = false"
                :dataList="visitNumList">
    </pop_select>
  </div>
</template>

<script>
import $qs from 'qs'
import Header from '../../../components/Vue/Header'
import PopSelect from '../../../components/Vue/PopSelect'
import Start_EndTime from '../../../assets/Time/Start_EndTime'
export default {
  name: 'VisitingScheduling',
  components: {
    Header,
    pop_select: PopSelect
  },
  data () {
    return {
      loadingShow: false,
      team_id: this.$route.query.team_id,
      tableData: [],
      minDate: new Date(new Date().getTime() + 24 * 60 * 60 * 1000), // 后一天,
      maxDate: new Date(2025, 10, 1),
      currentDate: new Date(),
      dateShow: false,
      row: [],
      Timecolumns: Start_EndTime.start_end30Time,
      TimeShow: false,
      selectList: [],
      cancelShow: false,
      date_ShaixuanShow: false,
      start_ShaixuanShow: false,
      end_ShaixuanShow: false,
      visit_ShaixuanShow: false,
      dateList: [],
      shartList: [],
      endList: [],
      visitNumList: []
    }
  },
  computed: {
    isShowtabbar () {
      if (this.$route.query.isShowtabbar || sessionStorage.getItem('isShowtabbar')) {
        return true
      } else {
        return false
      }
    },
    tabHeight () {
      let title = ''
      if (this.isShowtabbar) {
        title = 'calc(100vh - 44px  - 60px)'
      } else {
        title = 'calc(100vh - 44px - 60px - 50px)'
      }
      return title
    }
  },
  mounted () {
    this.$toast({
      message: '向左滑动查看更多',
      icon: 'like-o'
    })
    this.getList()
  },
  methods: {
    filter () {
      this.tableData = []
      this.loadingShow = true
      let dateday = ''
      let start_time = ''
      let end_time = ''
      let visit_num = ''
      this.dateList.forEach((curr) => {
        if (curr.select === true) {
          dateday += curr.value + ','
        }
      })
      this.shartList.forEach((curr) => {
        if (curr.select === true) {
          start_time += curr.value + ','
        }
      })
      this.endList.forEach((curr) => {
        if (curr.select === true) {
          end_time += curr.value + ','
        }
      })
      this.visitNumList.forEach((curr) => {
        if (curr.select === true) {
          visit_num += curr.value + ','
        }
      })
      dateday = dateday.substring(0, dateday.length - 1)
      start_time = start_time.substring(0, start_time.length - 1)
      end_time = end_time.substring(0, end_time.length - 1)
      visit_num = visit_num.substring(0, visit_num.length - 1)
      // {
      //   team_id: this.team_id,
      //     dateday: dateday,
      //   start_time: start_time,
      //   end_time: end_time,
      //   visit_num: visit_num
      // }
      let params = {
        team_id: this.team_id
      }
      if (dateday) {
        params.dateday = dateday
      }
      if (start_time) {
        params.start_time = start_time
      }
      if (end_time) {
        params.end_time = end_time
      }
      if (visit_num) {
        params.visit_num = visit_num
      }
      this.$http.findTeamVisitParam(params)
        .then(res => {
          console.log(res)
          if (res.data.status === 'success') {
            this.tableData = res.data.data.list
            this.loadingShow = false
          } else {
            this.$toast(res.data.msg)
          }
        })
        .catch(err => {
          console.log(err)
          this.$toast('您的网络有些拥挤，请稍后再试')
        })
    },
    clickDelete () {
      if (this.selectList.length > 0) {
        this.cancelShow = true
      } else {
        this.$toast('请先勾选数据')
      }
    },
    deleteConfirm () {
      this.$http.DelTeamVisitById({id: this.selectList[0].id})
        .then(res => {
          console.log(res)
          if (res.data.status === 'success') {
            this.cancelShow = false
            this.$toast('删除成功')
            this.getList()
          } else {
            this.$toast(res.data.msg)
          }
        })
        .catch(err => {
          console.log(err)
          this.$toast('您的网络有些拥挤，请稍后再试')
        })
    },
    // 选择时间段
    timeConfirm (value) {
      const [star, end] = value
      let row = JSON.parse(JSON.stringify(this.row))
      row.start_time = star
      row.end_time = end
      this.save(row)
      this.TimeShow = false
    },
    formatter (type, val) {
      if (type === 'year') {
        return `${val}年`
      } else if (type === 'month') {
        return `${val}月`
      } else if (type === 'day') {
        return `${val}日`
      }
      return val
    },
    // 选择日期确认
    dateConfirm () {
      this.row.dateday = this.Common.formatDate(this.currentDate, 'yyyy-mm-dd')
      this.save(this.row)
      this.dateShow = false
    },
    handleInputBlur (nowRow) {
      if (new Date().getTime() >= new Date(nowRow.dateday).getTime()) {
      } else {
        this.save(nowRow)
      }
    },
    handle (row, column, event, cell) {
      console.log(row)
      this.row = row
      if (new Date().getTime() >= new Date(row.dateday).getTime()) {
        this.$toast('历史数据不可修改')
        return false
      }
      if (column.property === 'dateday') {
        this.currentDate = new Date(row.dateday)
        this.dateShow = true
      } else if (column.property === 'start_time' || column.property === 'end_time') {
        this.TimeShow = true
      }
    },
    // 选中的项
    handleSelectionChange (val) {
      this.selectList = val
    },
    // 点击头部筛选
    tableHeader (column, event) {
      if (column.property === 'dateday') {
        this.date_ShaixuanShow = true
      } if (column.property === 'start_time') {
        this.start_ShaixuanShow = true
      } if (column.property === 'end_time') {
        this.end_ShaixuanShow = true
      } if (column.property === 'visit_num') {
        this.visit_ShaixuanShow = true
      }
    },
    // 给全选加class
    cellClass (row) {
      if (row.columnIndex == 0) {
        return 'disabledCheck'
      }
    },
    // 点击行单选
    handleRow (selection, row) {
      // 先清除所有选中的
      this.$refs.tables.clearSelection()
      // 当前的点击实现勾选
      this.$refs.tables.toggleRowSelection(row)
    },
    // 保存
    save (nowRow) {
      // let params = nowRow
      let params = {
        team_id: nowRow.team_id
      }
      if (nowRow.id) {
        params.id = nowRow.id
      }
      if (nowRow.dateday) {
        params.dateday = nowRow.dateday
      }
      if (nowRow.start_time) {
        params.start_time = nowRow.start_time
      }
      if (nowRow.end_time) {
        params.end_time = nowRow.end_time
      }
      if (nowRow.visit_num) {
        params.visit_num = nowRow.visit_num
      }
      this.$http.miniTeamVisitsave($qs.stringify(params))
        .then(res => {
          console.log(res)
          if (res.data.status === 'success') {
            this.getList()
          } else {
            this.$toast(res.data.msg)
          }
        })
        .catch(err => {
          console.log(err)
          this.$toast('您的网络有些拥挤，请稍后再试')
        })
    },
    add () {
      let obj = {
        id: '', //	ID不为空时修改
        team_id: this.team_id, //	团队ID
        dateday: '', // 探视日期，格式
        start_time: '', //	探视开始时间
        end_time: '', //	探视结束时间
        visit_num: '' //	人数
      }
      if (this.tableData.length > 0 && !this.tableData[this.tableData.length - 1].id) {
        this.$toast('请先维护上条数据')
        return false
      } else {
        this.tableData.push(obj)
      }
    },
    getList () {
      this.tableData = []

      this.dateList = []
      this.shartList = []
      this.endList = []
      this.visitNumList = []
      this.loadingShow = true
      this.$http.findTeamVisitParam({
        team_id: this.team_id
      })
        .then(res => {
          console.log(res)
          if (res.data.status === 'success') {
            let data = res.data.data
            this.tableData = res.data.data.list
            this.loadingShow = false
            data.datedayList.forEach((curr) => {
              let obj = {
                value: curr.dateday,
                text: this.Common.formatDate(curr.dateday, 'mm-dd')
              }
              this.dateList.push(obj)
            })
            data.startTimeList.forEach((curr) => {
              let obj = {
                value: curr.start_time,
                text: curr.start_time
              }
              this.shartList.push(obj)
            })
            data.endTimeList.forEach((curr) => {
              let obj = {
                value: curr.end_time,
                text: curr.end_time
              }
              this.endList.push(obj)
            })
            data.visitNumList.forEach((curr) => {
              let obj = {
                value: curr.visit_num,
                text: curr.visit_num + '人'
              }
              this.visitNumList.push(obj)
            })
          } else {
            this.$toast(res.data.msg)
          }
        })
        .catch(err => {
          console.log(err)
          this.$toast('您的网络有些拥挤，请稍后再试')
        })
    },
    renderHeader (h, {column}) { // h即为cerateElement的简写，具体可看vue官方文档
      return h(
        'span',
        [
          h('span', column.label),
          h('i', {
            class: 'el-icon-arrow-down',
            style: 'color:#fff;margin-left:5px;'
          })
        ]
      )
    },
    // 返回
    back () {
      this.$router.history.go(-1)
    }
  }
}
</script>

<style scoped lang="scss">
/deep/ .el-table .disabledCheck{
  .cell::before{
    content: '选择';
    text-align: center;
    line-height: 37px;
  }
  // 全选框隐藏
   .el-checkbox{
    display: none;
  }
}

/deep/ .el-table__empty-text{
  left: auto;
}

.keepBottom{
  width: 100%;
  height: 60px;
  background: #FFFFFF;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  box-sizing: border-box;
  position: sticky;
  bottom: 0px;
  button{
    width: 95%;
    height: 44px;
    border: 1px solid #1DA4F2;
    background: #FFFFFF;
    border-radius: 10px;
    font-size: 17px;
    font-weight: bold;
    color: #1da4f2;
    margin: 0 10px;
  }
}
/deep/ .el-checkbox__inner{
  border-radius: 50%;
}
</style>
